import functools
import MySQLdb
import random
import hashlib

create_connect = functools.partial(
       MySQLdb.connect, host='localhost', port=3306,
                       user='guest', password='123456',
                       charset='utf8mb4', autocommit=False)

KeyWord = ('1234567890'
           'qwertyuiopasdfghjklzxcvbnm'
           'ZXCVBNMLKJHGFDSAQWERTYUIOP')


def random_pass(length, candidate_characters=KeyWord):
    """生成指定长度的随机密码"""
    return ''.join(random.choices(candidate_characters, k=length))


def password_to_sha256(password):
    """生成密码的SHA256摘要(指纹)"""
    hasher = hashlib.sha256()
    hasher.update(password.encode())
    return hasher.hexdigest()


def password_to_MD5(password):
    """生成密码的md5摘要(指纹)"""
    hasher = hashlib.md5()
    hasher.update(password.encode())
    return hasher.hexdigest()


"""定义错误类"""


class NoSuchHashAlgorithException(Exception):
    pass


def password_to_digest(password , *,hash_alg='md5'):
    # 把密码变成指定的哈希摘要
    cls = getattr(hashlib, hash_alg.lower())
    if cls:
        hasher = cls()
        hasher.update(password.encode())
        return hasher.hexdigest()
        # 返回加密后的密码
    raise NoSuchHashAlgorithException(f'没有{hash_alg}哈希算法')


if __name__ == '__main__':
    print(password_to_digest('123456'))
    print(password_to_digest('123456', hash_alg='sha256'))
    print(password_to_digest('123456', hash_alg='MD5'))
